﻿using MediatR;
using PublicClass;
using S.Produce.Domains;
using S.Produce.Infrastructure;
using S.Produce.Read.Api.Application.Commands.PregnantCommands;

namespace S.Produce.Read.Api.Application.CommandHandlers.PregnantCommandHandlers
{
    /// <summary>
    /// 
    /// </summary>
    public class PregnantSelectCommandHandler : IRequestHandler<PregnantSelectCommand, PageInfo<Pregnant>>
    {
        private readonly IRepository<Pregnant> _repository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="repository"></param>
        public PregnantSelectCommandHandler(IRepository<Pregnant> repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PageInfo<Pregnant>> Handle(PregnantSelectCommand request, CancellationToken cancellationToken)
        {
            var pregnants = await _repository.GetAllAsync();
            var info = pregnants.AsQueryable().Where(x => !x.IsDel);
            if (!string.IsNullOrEmpty(request.PregnantDate))
            {
                var sdate = request.PregnantDate.Split(",")[0];
                var edate = request.PregnantDate.Split(",")[0];
                info = info.Where(x => x.PreDate >= DateTime.Parse(sdate) && x.PreDate <= DateTime.Parse(edate));
            }
            if (!string.IsNullOrEmpty(request.Earbugles))
            {
                info = info.Where(x => x.Earbugles == request.Earbugles);
            }
            if (!string.IsNullOrEmpty(request.Head))
            {
                info = info.Where(x => x.PersonCharge == request.Head);
            }
            if (!string.IsNullOrEmpty(request.PreResult))
            {
                info = info.Where(x => x.PreResult == request.PreResult);
            }
            if (request.PreNumber != 0)
            {
                info = info.Where(x => x.PreNumber == request.PreNumber);
            }
            int totalCount = info.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            info = info.OrderByDescending(x => x.CreateDate).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);
            return new PageInfo<Pregnant>()
            {
                datas = info.ToList(),
                pageCount = pageCount,
                totalCount = totalCount,
            };
        }
    }
}
